<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  listBookDescriptionService,
  addBookDescriptionService,
  updateBookDescriptionService,
  deleteBookDescriptionService,
} from "@/api/bookdescription.js";
import { addBookService } from "@/api/books.js";

const bookDescriptionData = ref([]);
const pageNum = ref(1);
const pageSize = ref(15);
const total = ref(10);
const showAddDialog = ref(false);
const showUpdateDialog = ref(false);
const showShelfDialog = ref(false);
const showBatchShelfDialog = ref(false);
const addFormRef = ref(null);
const updateFormRef = ref(null);
const shelfFormRef = ref(null);
const batchShelfFormRef = ref(null);
const selectedBooks = ref([]);

const newBookDescription = ref({
  bookName: "",
  description: "",
  price: "",
  language: "",
  isbn: "",
});

const shelfBook = ref({
  isbn: "",
  bookName: "",
  description: "",
  price: "",
  language: "",
  status: "未借阅",
  quantity: 1,
});

const batchShelf = ref({
  quantity: 1,
});

const searchBookDescription = ref({
  bookName: "",
  description: "",
  price: "",
  language: "",
  isbn: "",
});

const handleSizeChange = (size) => {
  pageSize.value = size;
  listBooksDescription();
};
const handleCurrentChange = (num) => {
  pageNum.value = num;
  listBooksDescription();
};

const listBooksDescription = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchBookDescription.value,
  };
  let result = await listBookDescriptionService(params);
  total.value = result.data.total;
  bookDescriptionData.value = result.data.records;
};

const reset = async () => {
  searchBookDescription.value.bookName = "";
  searchBookDescription.value.description = "";
  searchBookDescription.value.price = "";
  searchBookDescription.value.language = "";
  searchBookDescription.value.isbn = "";
  await listBooksDescription();
};

const addBookDescription = async () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      let addResult = await addBookDescriptionService(newBookDescription.value);
      if (addResult.code === 0) {
        showAddDialog.value = false;
        ElMessage.success("新增成功");
        await listBooksDescription();
      } else {
        ElMessage.error("新增失败");
      }
    }
  });
};

const updateBookDescription = async () => {
  updateFormRef.value.validate(async (valid) => {
    if (valid) {
      let updateResult = await updateBookDescriptionService(
        newBookDescription.value,
      );
      if (updateResult.code === 0) {
        showUpdateDialog.value = false;
        ElMessage.success("更新成功");
        await listBooksDescription();
      } else {
        ElMessage.error("更新失败");
      }
    }
  });
};

const deleteBookDescription = async (isbn) => {
  ElMessageBox.confirm("此操作将永久删除该书籍, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let deleteResult = await deleteBookDescriptionService(isbn);
      if (deleteResult.code === 0) {
        ElMessage.success("删除成功");
        await listBooksDescription();
      } else {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const viewAdd = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  newBookDescription.value.bookName = "";
  newBookDescription.value.description = "";
  newBookDescription.value.price = "";
  newBookDescription.value.language = "";
  newBookDescription.value.isbn = "";
  showAddDialog.value = true;
};

const viewUpdate = (row) => {
  if (updateFormRef.value) {
    updateFormRef.value.resetFields();
  }
  newBookDescription.value = { ...row };
  showUpdateDialog.value = true;
};

const viewShelf = (row) => {
  if (shelfFormRef.value) {
    shelfFormRef.value.resetFields();
  }
  shelfBook.value = { ...row, quantity: 1, status: "未借阅" };
  showShelfDialog.value = true;
};

const confirmBatchDelete = () => {
  ElMessageBox.confirm("此操作将永久删除选中的书籍, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      for (let book of selectedBooks.value) {
        await deleteBookDescriptionService(book.isbn);
      }
      ElMessage.success("批量删除成功");
      await listBooksDescription();
    })
    .catch(() => {
      ElMessage.info("已取消批量删除");
    });
};

const confirmBatchShelf = () => {
  if (selectedBooks.value.length === 0) {
    ElMessage.error("请先选择要上架的书籍");
    return;
  }
  showBatchShelfDialog.value = true;
};

const handleBatchShelf = async () => {
  batchShelfFormRef.value.validate(async (valid) => {
    if (valid) {
      const addPromises = selectedBooks.value.map((book) => {
        return addBookService({
          isbn: book.isbn,
          status: "未借阅",
          quantity: parseInt(batchShelf.value.quantity, 10),
        });
      });
      await Promise.all(addPromises);
      showBatchShelfDialog.value = false;
      ElMessage.success("批量上架成功");
      await listBooksDescription();
    }
  });
};

const addBook = async () => {
  shelfFormRef.value.validate(async (valid) => {
    if (valid) {
      let bookData = {
        isbn: shelfBook.value.isbn,
        status: shelfBook.value.status,
        quantity: parseInt(shelfBook.value.quantity, 10),
      };
      let bookResult = await addBookService(bookData);
      if (bookResult.code === 0) {
        showShelfDialog.value = false;
        ElMessage.success("上架成功");
        await listBooksDescription();
      } else {
        ElMessage.error("上架失败");
      }
    }
  });
};

const handleSelectionChange = (val) => {
  selectedBooks.value = val;
};

const filterHandler = (value, row, column) => {
  const property = column.property;
  return row[property] === value;
};

const rules = {
  isbn: [
    { required: true, message: "请输入书籍ISBN", trigger: "blur" },
    { pattern: /^[0-9]+$/, message: "ISBN格式不正确", trigger: "blur" },
  ],
  bookName: [{ required: true, message: "请输入书名", trigger: "blur" }],
  description: [{ required: true, message: "请输入书籍描述", trigger: "blur" }],
  price: [
    { required: true, message: "请输入书籍价格", trigger: "blur" },
    {
      pattern: /^[0-9]+(\.[0-9]+)?$/,
      message: "价格格式不正确",
      trigger: "blur",
    },
  ],
  language: [{ required: true, message: "请输入书籍语言", trigger: "blur" }],
};

const shelfRules = {
  quantity: [
    { required: true, message: "请输入上架数量", trigger: "blur" },
    {
      pattern: /^[1-9][0-9]*$/,
      message: "数量必须为大于0的整数",
      trigger: "blur",
    },
  ],
};

listBooksDescription();
</script>

<template>
  <div class="search-container">
    <el-input
      v-model="searchBookDescription.isbn"
      placeholder="请输入书籍ISBN"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBookDescription.bookName"
      placeholder="请输入书籍名称"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBookDescription.description"
      placeholder="请输入书籍描述"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBookDescription.price"
      placeholder="请输入书籍价格"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBookDescription.language"
      placeholder="请输入书籍语言"
      clearable
      class="search-input"
    />
  </div>
  <div class="button-group">
    <div class="extra-buttons">
      <el-button
        type="danger"
        @click="confirmBatchDelete"
        :disabled="selectedBooks.length === 0"
        icon="RemoveFilled"
        >批量删除</el-button
      >
      <el-button
        type="primary"
        @click="confirmBatchShelf"
        :disabled="selectedBooks.length === 0"
        icon="Histogram"
        >批量上架</el-button
      >
    </div>
    <el-button @click="listBooksDescription" type="primary" icon="Search"
      >搜索</el-button
    >
    <el-button @click="reset" type="warning" icon="RefreshRight"
      >重置</el-button
    >
    <el-button type="success" @click="viewAdd" icon="CirclePlus"
      >新增书籍描述</el-button
    >
  </div>

  <el-table
    :data="bookDescriptionData"
    :header-cell-style="{ background: '#2a598a', color: '#ffffff' }"
    border
    stripe
    :max-height="500"
    style="width: 100%"
    highlight-current-row
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="40" />
    <el-table-column sortable fixed prop="isbn" label="ISBN" width="140" />
    <el-table-column sortable prop="bookName" label="书名" min-width="130" />
    <el-table-column sortable prop="description" label="描述" min-width="120" />
    <el-table-column sortable prop="price" label="价格" min-width="120" />
    <el-table-column
      sortable
      min-width="120"
      prop="language"
      label="语言"
      :filters="[
        { text: '中文', value: '中文' },
        { text: '外文', value: '外文' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column label="操作" align="center" fixed="right" width="300">
      <template #default="scope">
        <el-button type="warning" @click="viewUpdate(scope.row)" icon="Refresh"
          >更新</el-button
        >
        <el-button
          type="danger"
          @click="deleteBookDescription(scope.row.isbn)"
          icon="delete"
          >删除</el-button
        >
        <el-button type="primary" @click="viewShelf(scope.row)" icon="Check"
          >上架</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageNum"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20, 30, 50, 100]"
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px; justify-content: flex-end"
  />

  <el-dialog title="新增书籍描述" v-model="showAddDialog" width="500">
    <el-form :model="newBookDescription" :rules="rules" ref="addFormRef">
      <el-form-item label="ISBN" prop="isbn">
        <el-input v-model="newBookDescription.isbn"></el-input>
      </el-form-item>
      <el-form-item label="书名" prop="bookName">
        <el-input v-model="newBookDescription.bookName"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="newBookDescription.description"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="newBookDescription.price"></el-input>
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-radio-group v-model="newBookDescription.language">
          <el-radio value="中文">中文</el-radio>
          <el-radio value="外文">外文</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="addBookDescription">确定</el-button>
    </span>
  </el-dialog>

  <el-dialog title="更新图书描述" v-model="showUpdateDialog" width="500">
    <el-form :model="newBookDescription" :rules="rules" ref="updateFormRef">
      <el-form-item label="ISBN" prop="isbn">
        <el-input v-model="newBookDescription.isbn" disabled></el-input>
      </el-form-item>
      <el-form-item label="书名" prop="bookName">
        <el-input v-model="newBookDescription.bookName"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="newBookDescription.description"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="newBookDescription.price"></el-input>
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-radio-group v-model="newBookDescription.language">
          <el-radio value="中文">中文</el-radio>
          <el-radio value="外文">外文</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showUpdateDialog = false">取消</el-button>
      <el-button type="primary" @click="updateBookDescription">确定</el-button>
    </span>
  </el-dialog>

  <el-dialog title="上架书籍" v-model="showShelfDialog" width="500">
    <el-form :model="shelfBook" :rules="shelfRules" ref="shelfFormRef">
      <el-form-item label="ISBN" prop="isbn">
        <el-input v-model="shelfBook.isbn" disabled></el-input>
      </el-form-item>
      <el-form-item label="书名" prop="bookName">
        <el-input v-model="shelfBook.bookName" disabled></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="shelfBook.description" disabled></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="shelfBook.price" disabled></el-input>
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-input v-model="shelfBook.language" disabled></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input v-model="shelfBook.status" disabled></el-input>
      </el-form-item>
      <el-form-item label="数量" prop="quantity">
        <el-input v-model="shelfBook.quantity"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showShelfDialog = false">取消</el-button>
      <el-button type="primary" @click="addBook">确定</el-button>
    </span>
  </el-dialog>

  <el-dialog title="批量上架" v-model="showBatchShelfDialog" width="500">
    <el-form :model="batchShelf" :rules="shelfRules" ref="batchShelfFormRef">
      <el-form-item label="上架数量" prop="quantity">
        <el-input v-model="batchShelf.quantity"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showBatchShelfDialog = false">取消</el-button>
      <el-button type="primary" @click="handleBatchShelf">确定</el-button>
    </span>
  </el-dialog>

  <el-dialog title="批量上架" v-model="showBatchShelfDialog" width="500">
    <el-form :model="batchShelf" :rules="shelfRules" ref="batchShelfFormRef">
      <el-form-item label="上架数量" prop="quantity">
        <el-input v-model="batchShelf.quantity"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="showBatchShelfDialog = false">取消</el-button>
      <el-button type="primary" @click="handleBatchShelf">确定</el-button>
    </span>
  </el-dialog>
</template>

<style scoped>
.button-group {
  display: flex;
  gap: 5px;
  justify-content: flex-end;
  margin-bottom: 10px;
}
</style>
